<template>
  <HeaderComponent />
  <div class="canteen-detail-container">
    <!-- 左侧导航栏 -->
    <div class="sidebar">
      <el-menu :default-active="activeMenu"
               width="200px"
               class="el-menu-vertical-demo" @select="handleMenuSelect">
        <button class="back-button" @click="goBack">返回</button>
        <span>{{ canteenName }}</span>
        <el-menu-item index="tables">
          <span>餐桌</span>
        </el-menu-item>
        <el-menu-item index="dishes">
          <span>菜品</span>
        </el-menu-item>
        <el-menu-item index="reviews">
          <span>餐厅评价</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧内容 -->
    <div class="content">
      <!-- 餐桌选择 -->
      <div v-if="activeMenu === 'tables'" class="tables-section">
        <h2>餐桌选择</h2>
        <div class="table-list">
          <div v-for="table in tables" :key="table.id" class="table-item">
            <div class="table-info">
              <span>{{ table.number }}号桌</span>
              <span>可坐{{ table.capacity }}人</span>
              <span>价格: {{ table.price }}元</span>
              <span v-if="table.status === 1" style="color: red;">已被预订</span>
              <span v-else style="color: green;">空闲</span>
            </div>
            <!-- 普通用户显示选择按钮 -->
            <el-button
                v-if="userType !== '0'"
                type="primary"
                @click="openConfirmModal(table.id)"
                :disabled="table.status === 1"
            >
              预定
            </el-button>
            <!-- 管理员显示编辑和删除按钮 -->
            <div v-else>
              <el-button type="primary" @click="openEditModal(table)">编辑</el-button>
              <el-button type="danger" @click="deleteTable(table.id)">删除</el-button>
            </div>
          </div>
        </div>
        <!-- 添加餐桌按钮（仅管理员可见） -->
        <el-button v-if="userType === '0'" type="success" @click="openAddTableModal">添加餐桌</el-button>
      </div>
      <!-- 添加餐桌弹框 -->
      <el-dialog v-model="addTableModalVisible" title="添加餐桌" width="30%">
        <el-form :model="addTableForm" label-width="80px">
          <el-form-item label="座位号">
            <el-input v-model="addTableForm.number" />
          </el-form-item>
          <el-form-item label="容量">
            <el-input v-model="addTableForm.capacity" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="addTableForm.price" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addTableModalVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddTable">确定</el-button>
        </template>
      </el-dialog>
      <!-- 确认支付弹框 -->
      <el-dialog v-model="confirmModalVisible" title="确认支付" width="30%">
        <p>确认支付 {{ selectedTablePrice }} 元吗？</p>
        <template #footer>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </template>
      </el-dialog>
      <!-- 编辑座位弹框 -->
      <el-dialog v-model="editModalVisible" title="编辑座位" width="30%">
        <el-form :model="editForm" label-width="80px">
          <el-form-item label="座位号">
            <el-input v-model="editForm.number" />
          </el-form-item>
          <el-form-item label="容量">
            <el-input v-model="editForm.capacity" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="editForm.price" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="editForm.status">
              <el-option label="空闲" :value="0" />
              <el-option label="已预订" :value="1" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editModalVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEdit">保存</el-button>
        </template>
      </el-dialog>

      <!-- 菜品 -->
      <div v-if="activeMenu === 'dishes'" class="dishes-section">
        <h2>菜品</h2>
        <div class="dish-list">
          <div v-for="dish in dishes" :key="dish.id" class="dish-item">
            <img :src="require(`../assets/uploads/${dish.image}`)"
                 alt="菜品图片"
                 style="width: 50%; height: auto; border-radius: 4px; margin-top: 10px;"
                 class="dish-image"
            />
            <div class="dish-info">
              <h3>{{ dish.name }}</h3>
              <p>价格: {{ dish.price }}元</p>
              <p>类型: {{ dish.typeName }}</p>
            </div>
            <!-- 管理员显示编辑和删除按钮 -->
            <div v-if="userType === '0'" class="dish-actions">
              <el-button type="primary" @click="openEditDishModal(dish)">编辑</el-button>
              <el-button type="danger" @click="openDeleteDishModal(dish.id)">删除</el-button>
            </div>
          </div>
        </div>
        <!-- 添加菜品按钮（仅管理员可见） -->
        <el-button v-if="userType === '0'" type="success" @click="openAddDishModal">添加菜品</el-button>
      </div>

      <!-- 编辑菜品弹框 -->
      <el-dialog v-model="editDishModalVisible" title="编辑菜品" width="30%">
        <el-form :model="editDishForm" label-width="80px">
          <el-form-item label="菜品名称">
            <el-input v-model="editDishForm.name" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="editDishForm.price" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="editDishForm.description" type="textarea" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="editDishForm.typeId" placeholder="请选择菜品类型">
              <el-option
                  v-for="type in dishTypes"
                  :key="type.id"
                  :label="type.name"
                  :value="type.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="图片">
            <input type="file" @change="handleEditDishImageUpload" accept="image/*" />
            <img v-if="editDishImagePreview" :src="editDishImagePreview" alt="预览图片" style="width: 100px; height: auto; margin-top: 10px;" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDishModalVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditDish">确定</el-button>
        </template>
      </el-dialog>

      <!-- 删除菜品确认弹框 -->
      <el-dialog v-model="deleteDishModalVisible" title="确认删除" width="30%">
        <p>确定要删除该菜品吗？</p>
        <template #footer>
          <el-button @click="deleteDishModalVisible = false">取消</el-button>
          <el-button type="danger" @click="handleDeleteDish">确定</el-button>
        </template>
      </el-dialog>

      <!-- 添加菜品弹框 -->
      <el-dialog v-model="addDishModalVisible" title="添加菜品" width="40%">
        <el-form :model="addDishForm" label-width="80px">
          <el-form-item label="菜品名称">
            <el-input v-model="addDishForm.name" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="addDishForm.price" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="addDishForm.description" type="textarea" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="addDishForm.typeId" placeholder="请选择菜品类型">
              <el-option
                  v-for="type in dishTypes"
                  :key="type.id"
                  :label="type.name"
                  :value="type.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="图片">
            <input type="file" @change="handleAddDishImageUpload" accept="image/*" />
            <img v-if="addDishImagePreview" :src="addDishImagePreview" alt="预览图片" style="width: 100px; height: auto; margin-top: 10px;" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addDishModalVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddDish">确定</el-button>
        </template>
      </el-dialog>

      <!-- 餐厅评价 -->
      <div v-if="activeMenu === 'reviews'" class="reviews-section">
        <h2>餐厅评价</h2>
        <!-- 发布评价部分 -->
        <div class="create-post">
          <textarea
              @click="openModal"
              placeholder="有什么美食攻略想告诉大家？"
              readonly
          ></textarea>
        </div>

        <!-- 模态框 -->
        <div v-if="isModalOpen" class="modal-overlay">
          <div class="modal">
            <div class="modal-header">
              <h3>发布评价</h3>
              <button @click="closeModal" class="close-button">&times;</button>
            </div>
            <div class="modal-content">
              <textarea
                  v-model="newPostContent"
                  placeholder="写下你想分享的内容..."
              ></textarea>
              <input
                  type="file"
                  @change="handleImageUpload"
                  accept="image/*"
                  class="file-input"
              />
              <div v-if="imagePreview" class="image-preview">
                <img :src="imagePreview" alt="预览图片" style="width: 30%; height: auto; border-radius: 4px; margin-top: 10px;"/>
                <button @click="removeImage" class="remove-image-button">移除图片</button>
              </div>
            </div>
            <div class="modal-actions">
              <button @click="publishPost" class="publish-button">发布</button>
            </div>
          </div>
        </div>

        <!-- 评价列表 -->
        <div class="review-list">
          <div v-for="review in reviews" :key="review.id" class="review-item">
            <div class="review-header">
              <div class="user-info">
                <span class="username">{{ review.userName }}</span>
                <span class="review-time">{{ formatDate(review.date) }}</span>
              </div>
              <button
                  @click="deleteReview(review.id)"
                  class="delete-button"
                  v-if="review.userId === userId"
              >
                删除
              </button>
            </div>
            <div class="review-content">
              <p>{{ review.content }}</p>
              <div class="review-images">
                <img
                    v-if="review.image"
                    :src="require(`../assets/uploads/${review.image}`)"
                    alt="评价图片"
                    style="width: 30%; height: auto; border-radius: 4px; margin-top: 10px;"
                    class="review-image"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import HeaderComponent from "@/components/HeaderComponent.vue";
import {
  GetCanteenTable,
  GetDishes,
  BookTable,
  GetReview,
  AddReview,
  DeleteReview,
  GetCanteenDetail,
  UpdateSeat,
  DeleteSeat,
  AddSeat,
  AddDish,
  DeleteDish,
  UpdateDish,
  GetDishType,
} from "@/api";
import {ElMessage} from "element-plus";
import store from "@/store"; // 引入相关接口

export default {
  name: 'CanteenInfoVue',
  components: { HeaderComponent },
  setup() {

    // 页面加载时获取餐桌数据
    onMounted(() => {
      fetchTables();
      fetchCanteenDetail();
      fetchDishTypes(); // 获取菜品类型数据
    });
    const route = useRoute();
    const router = useRouter();

    // 获取路由参数中的 canteenId
    const canteenId = ref(route.params.canteenId);
    const canteenName = ref(''); // 假设餐厅名称

    // 当前选中的菜单
    const activeMenu = ref('tables');

    // 餐桌数据
    const tables = ref([]);

    //支付宝相关
    // eslint-disable-next-line no-undef
    // const note = ref('') // 备注信息
    // const address = ref({
    //   id: 0,
    //   consignee: ''
    // })

    //用户类型
    const userType = ref(localStorage.getItem('type'));
    const userId = ref(localStorage.getItem('userId'));

    // 编辑弹框相关状态
    const editModalVisible = ref(false);
    const editForm = ref({
      id: null,
      number: null,
      capacity: null,
      price: null,
      status: null,
    });

    // 确认支付弹框相关状态
    const confirmModalVisible = ref(false);
    const selectedTableId = ref(null);
    const selectedTablePrice = ref(0);

    // 菜品数据
    const dishes = ref([]);

    // 评价数据
    const reviews = ref([]);

    // 发布评价相关状态
    const isModalOpen = ref(false);
    const newPostContent = ref('');
    const imageFile = ref(null);
    const imagePreview = ref('');

    // 添加餐桌弹框相关状态
    const addTableModalVisible = ref(false);
    const addTableForm = ref({
      number: null,
      capacity: null,
      price: null,
    });

    // 编辑菜品弹框相关状态
    const editDishModalVisible = ref(false);
    const editDishForm = ref({
      id: null,
      name: '',
      price: null,
      description: '',
      typeId: '',
      image: '',
    });
    const editDishImageFile = ref(null);
    const editDishImagePreview = ref('');

    // 删除菜品弹框相关状态
    const deleteDishModalVisible = ref(false);
    const selectedDishId = ref(null);

    // 添加菜品弹框相关状态
    const addDishModalVisible = ref(false);
    const addDishForm = ref({
      name: '',
      price: null,
      description: '',
      typeId: null, // 菜品类型ID
      image: '',
    });
    const addDishImageFile = ref(null);
    const addDishImagePreview = ref('');

    // 菜品类型数据
    const dishTypes = ref([]);

    // 打开添加餐桌弹框
    const openAddTableModal = () => {
      addTableForm.value = { number: null, capacity: null, price: null }; // 清空表单
      addTableModalVisible.value = true;
    };

    // 处理添加餐桌
    const handleAddTable = async () => {
      try {
        const response = await AddSeat(
            canteenId.value,
            addTableForm.value.number,
            addTableForm.value.capacity,
            addTableForm.value.price
        );
        if (response.data.code === 200) {
          ElMessage.success("添加成功");
          addTableModalVisible.value = false;
          await fetchTables(); // 重新获取餐桌数据
          console.log("添加成功:", response);
        } else {
          console.log("添加失败:", response.data);
          ElMessage.error("添加失败：" + response.data.errorMsg);
        }
      } catch (error) {
        console.error("添加失败:", error);
        ElMessage.error("添加失败" + error);
      }
    };


    //获取餐厅数据
    const fetchCanteenDetail = async () => {

      console.log('userType:', userType)

      try {
        const response = await GetCanteenDetail(canteenId.value);
        canteenName.value = response.data.data.name;
        if (response.data.code === 200) {
          canteenName.value = response.data.data.name;
          console.log("获取餐厅数据成功:", response);
        } else {
          console.error("获取餐厅数据失败:", response.data.errorMsg);
        }
      } catch (error) {
        console.error("获取餐厅数据失败:", error);
      }
    }

    // 获取餐桌数据
    const fetchTables = async () => {
      try {
        const response = await GetCanteenTable(canteenId.value);
        console.log("canteenId：", canteenId.value);
        if (response.data.code === 200) {
          tables.value = response.data.data;

        } else {
          console.error("获取餐桌数据失败:", response.data.errorMsg);
        }
      } catch (error) {
        console.error("获取餐桌数据失败:", error);
      }
    };

    // 获取菜品数据
    const fetchDishes = async () => {
      try {
        const response = await GetDishes(canteenId.value);
        if (response.data.code === 200) {
          dishes.value = response.data.data.dishes;
        } else {
          console.error("获取菜品数据失败:", response.data.errorMsg);
        }
      } catch (error) {
        console.error("获取菜品数据失败:", error);
      }
    };

    // 获取评价数据
    const fetchReviews = async () => {
      try {
        const response = await GetReview(canteenId.value);
        if (response.data.code === 200) {
          reviews.value = response.data.data.map(review => ({
            ...review,
            image: review.image // 设置默认图片
          }));
        } else {
          console.error("获取评价数据失败:", response.data.errorMsg);
        }
      } catch (error) {
        console.error("获取评价数据失败:", error);
      }
    };

    // 格式化日期
    const formatDate = (date) => {
      return new Date(date).toLocaleString();
    };

    // 处理菜单选择
    const handleMenuSelect = (index) => {
      activeMenu.value = index;
      if (index === 'tables') {
        fetchTables();
      } else if (index === 'dishes') {
        fetchDishes();
      } else if (index === 'reviews') {
        fetchReviews();
      }
    };

    // 打开确认支付弹框
    const openConfirmModal = (tableId) => {
      const table = tables.value.find((t) => t.id === tableId);
      if (table) {
        selectedTableId.value = tableId;
        selectedTablePrice.value = table.price;
        confirmModalVisible.value = true;
      }
      console.log("selectedTableId:", selectedTableId.value)
      console.log("selectedTablePrice:", selectedTablePrice.value)
      console.log("confirmModalVisible:", confirmModalVisible.value)
    };

    // 处理取消
    const handleCancel = async () => {
      confirmModalVisible.value = false;
      try {
        const response = await selectTable(selectedTableId.value, 0);
        if (response.data.code === 200) {
          ElMessage.success("已取消支付");
          await fetchTables(); // 重新获取餐桌数据
        } else {
          ElMessage.error("操作失败：" + response.data.errorMsg);
        }
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败，请稍后重试");
      }
    };

    // 处理确认
    const handleConfirm = async () => {
      confirmModalVisible.value = false;
      try {
        const response = await selectTable(selectedTableId.value, 0);
        if (response.data.code === 200) {
          // const res = await BookTable(response.data.data.id, 0)
          // console.log('res:', res);
          // if(res.code === 1){
          //   window.open(`http://localhost:8081/api/alipay/pay?orderId=${res.data.data.id}`)
          //   this.$message.success('付款成功')
          //   this.load();
          // } else{
          // this.$notify({ type:'warning', message:res.msg});
          // }

          // const result = reqAliPay(response.data.data.id);
          // console.log("result:", result)
          // const htmlContent = result.data;
          // const blob = new Blob([htmlContent], { type: 'text/html' });
          // const url = URL.createObjectURL(blob);
          // window.open(url, '_self');

          // await store.dispatch('/modules/reqPay', {
          //   orderId: response.data.data.id
          // }).then(
          //     res=>{
          //       console.log("res:", res)
          //       this.$message.success('付款成功')
          //       // this.$router.push({ path: '/modules/orderList' });
          //     }
          // )

          console.log("response:", response.data.data)
          const orderId = response.data.data.id;
          const paymentResponse = await store.dispatch('order/reqPay', {
            orderId
          });
          if (paymentResponse) {
            console.log("res:", paymentResponse);
            // ElMessage.success('付款成功');
            // this.$router.push({ path: '/modules/orderList' });
          }

          // ElMessage.success("已确认支付");
          await fetchTables(); // 重新获取餐桌数据
        } else {
          ElMessage.error("支付失败：" + response.data.errorMsg);
        }
      }catch (error){
        console.error("支付失败:", error);
        // ElMessage.error("支付失败，请稍后重试");
      }
    };
    // const handleConfirm = async () => {
    //   confirmModalVisible.value = false;
    //   try {
    //     const params = {
    //       remark: note.value,          // 假设你有note这个ref
    //       payMethod: 1,               // 支付方式
    //       addressBookId: address.value.id  // 假设你有address这个ref
    //     };
    //     const response = await selectTable(selectedTableId.value, 0);
    //     // 支付宝支付跳转（根据你的业务需要决定是否保留）
    //     // window.open(`http://localhost:8081/alipay/pay?subject=${response.data.data.userName.trim()}
    //     //     &traceNo=${response.data.data.id}&totalAmount=${response.data.data.orderAmount}`);
    //     window.open(pay(response.data.data.id));
    //     console.log('userName', response.data.data.userName)
    //     console.log('请求参数:', params);
    //     console.log('响应结果:', response);
    //     if (response.data.code === 200) {
    //       // await selectTable(selectedTableId.value, 1);
    //       ElMessage.success("支付成功");
    //       // await fetchTables(); // 重新获取餐桌数据
    //     } else {
    //       ElMessage.error("支付失败：" + response.data.message);
    //     }
    //   } catch (error) {
    //     console.error("支付失败:", error);
    //     ElMessage.error("支付失败，请稍后重试");
    //   }
    // };

    // 选择餐桌
    const selectTable = async (seatId, status) => {
      try {
        const response = await BookTable(seatId, status);
        return response;
      } catch (error) {
        console.error("操作失败:", error);
        throw error;
      }
    };

    // 打开编辑弹框
    const openEditModal = (table) => {
      editForm.value = { ...table }; // 填充当前座位数据
      editModalVisible.value = true;
    };

    // 保存编辑
    const saveEdit = async () => {
      try {
        console.log("editForm:", editForm.value)
        const response = await UpdateSeat(editForm.value.id,
        editForm.value.capacity, editForm.value.price,
        editForm.value.number, editForm.value.status);
        if (response.data.code === 200) {
          ElMessage.success("修改成功");
          editModalVisible.value = false;
          await fetchTables(); // 重新获取餐桌数据
        } else {
          ElMessage.error("修改失败：" + response.data.errorMsg);
        }
      } catch (error) {
        console.error("修改失败:", error);
        ElMessage.error("修改失败, 请稍后重试");
      }
    };

    // 删除座位
    const deleteTable = async (seatId) => {
      try {
        const response = await DeleteSeat(seatId);
        if (response.data.code === 200) {
          ElMessage.success("删除成功");
          fetchTables(); // 重新获取餐桌数据
        } else {
          ElMessage.error("删除失败：" + response.data.errorMsg);
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败，请稍后重试");
      }
    };

    // 发布评价
    const publishPost = async () => {

      if (!newPostContent.value.trim() && !imageFile.value) {
        ElMessage.error("请填写内容或上传图片");
        return;
      }

      const formData = new FormData();
      formData.append('canteenId', canteenId.value);
      formData.append('content', newPostContent.value);
      if (imageFile.value) {
        formData.append('image', imageFile.value);
      }

      // 调试信息
      for (let [key, value] of formData.entries()) {
        console.log(key, value);
      }

      try {
        const response = await AddReview(formData);
        if (response.data.code === 200) {
          ElMessage.success("发布成功");
          closeModal();
          setTimeout(() => {
            fetchReviews(); // 重新获取评价数据
          }, 1000);
        } else {
          ElMessage.error("发布失败：" + response.data.errorMsg);
        }
      } catch (error) {
        console.error("发布失败:", error);
        ElMessage.error("发布失败，请稍后重试");
      }
    };

    // 删除评价
    const deleteReview = async (reviewId) => {
      try {
        const response = await DeleteReview(reviewId);
        if (response.data.code === 200) {
          ElMessage.success("删除成功");
          await fetchReviews(); // 重新获取评价数据
        } else {
          ElMessage.error("删除失败：" + response.data.errorMsg);
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败，请稍后重试");
      }
    };

    // 返回按钮点击事件
    const goBack = () => {
      router.push('/canteen');
    };

    // 打开模态框
    const openModal = () => {
      isModalOpen.value = true;
    };

    // 关闭模态框
    const closeModal = () => {
      isModalOpen.value = false;
      newPostContent.value = '';
      imageFile.value = null;
      imagePreview.value = '';
    };

    // 处理图片上传
    const handleImageUpload = (event) => {
      const file = event.target.files[0];
      if (file) {
        imageFile.value = file;
        imagePreview.value = URL.createObjectURL(file);
      }
    };

    // 移除图片
    const removeImage = () => {
      imageFile.value = null;
      imagePreview.value = '';
    };

    // 打开编辑菜品弹框
    const openEditDishModal = (dish) => {
      editDishForm.value = { ...dish, typeId: dish.typeId }; // 填充当前菜品数据，包括 typeId
      editDishImagePreview.value = require(`../assets/uploads/${dish.image}`);
      editDishModalVisible.value = true;
    };

    // 处理编辑菜品图片上传
    const handleEditDishImageUpload = (event) => {
      const file = event.target.files[0];
      if (file) {
        editDishImageFile.value = file;
        editDishImagePreview.value = URL.createObjectURL(file);
      }
    };

    // 处理编辑菜品
    const handleEditDish = async () => {
      try {
        const formData = new FormData();
        formData.append('id', editDishForm.value.id);
        formData.append('name', editDishForm.value.name);
        formData.append('price', editDishForm.value.price);
        formData.append('description', editDishForm.value.description);
        formData.append('type', editDishForm.value.typeId); // 传递菜品类型ID
        if (editDishImageFile.value) {
          formData.append('image', editDishImageFile.value);
        }

        const response = await UpdateDish(formData);
        if (response.data.code === 200) {
          ElMessage.success("修改成功");
          editDishModalVisible.value = false;
          setTimeout(() => {
            fetchDishes(); // 重新获取菜品数据
          }, 1000);
        } else {
          ElMessage.error("修改失败：" + response.data.errorMsg);
        }
      } catch (error) {
        console.error("修改失败:", error);
        ElMessage.error("修改失败，请稍后重试");
      }
    };

    // 打开删除菜品确认弹框
    const openDeleteDishModal = (dishId) => {
      selectedDishId.value = dishId;
      deleteDishModalVisible.value = true;
    };

    // 处理删除菜品
    const handleDeleteDish = async () => {
      try {
        const response = await DeleteDish(selectedDishId.value);
        if (response.data.code === 200) {
          ElMessage.success("删除成功");
          deleteDishModalVisible.value = false;
          await fetchDishes(); // 重新获取菜品数据
        } else {
          ElMessage.error("删除失败：" + response.data.errorMsg);
          console.error("删除失败：", response);
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败，请稍后重试");
      }
    };

    // 打开添加菜品弹框
    const openAddDishModal = () => {
      addDishForm.value = { name: '', price: null, description: '', type: '', image: '' };
      addDishImagePreview.value = '';
      addDishModalVisible.value = true;
    };

    // 处理添加菜品图片上传
    const handleAddDishImageUpload = (event) => {
      const file = event.target.files[0];
      if (file) {
        addDishImageFile.value = file;
        addDishImagePreview.value = URL.createObjectURL(file);
      }
    };

    // 处理添加菜品
    const handleAddDish = async () => {
      try {
        const formData = new FormData();
        formData.append('canteenId', canteenId.value);
        formData.append('name', addDishForm.value.name);
        formData.append('price', addDishForm.value.price);
        formData.append('description', addDishForm.value.description);
        formData.append('type', addDishForm.value.typeId); // 传递菜品类型ID
        if (addDishImageFile.value) {
          formData.append('image', addDishImageFile.value);
        }

        const response = await AddDish(formData);
        if (response.data.code === 200) {
          ElMessage.success("添加成功");
          addDishModalVisible.value = false;
          setTimeout(() => {
            fetchDishes(); // 重新获取菜品数据
          }, 1000);
        } else {
          ElMessage.error("添加失败：" + response.data.message);
        }
      } catch (error) {
        console.error("添加失败:", error);
        ElMessage.error("添加失败，请稍后重试");
      }
    };

    // 获取菜品类型数据
    const fetchDishTypes = async () => {
      try {
        const response = await GetDishType();
        if (response.data.code === 200) {
          dishTypes.value = response.data.data;
        } else {
          console.error("获取菜品类型失败:", response.data.message);
        }
      } catch (error) {
        console.error("获取菜品类型失败:", error);
      }
    };

    return {
      canteenName,
      activeMenu,
      tables,
      userType,
      editModalVisible,
      editForm,
      dishes,
      reviews,
      isModalOpen,
      newPostContent,
      imagePreview,
      confirmModalVisible,
      selectedTablePrice,
      addTableModalVisible,
      addTableForm,
      openAddTableModal,
      handleAddTable,
      fetchCanteenDetail,
      handleMenuSelect,
      selectTable,
      openEditModal,
      saveEdit,
      deleteTable,
      publishPost,
      deleteReview,
      goBack,
      openModal,
      closeModal,
      handleImageUpload,
      removeImage,
      formatDate,
      openConfirmModal,
      handleCancel,
      handleConfirm,
      editDishModalVisible ,
      editDishForm,
      editDishImageFile ,
      editDishImagePreview ,
      deleteDishModalVisible ,
      selectedDishId,
      addDishModalVisible ,
      addDishForm ,
      addDishImageFile ,
      addDishImagePreview ,
      openEditDishModal ,
      handleEditDishImageUpload ,
      handleEditDish ,
      openDeleteDishModal ,
      handleDeleteDish ,
      openAddDishModal ,
      handleAddDishImageUpload ,
      handleAddDish,
      dishTypes,
      fetchDishTypes,
      userId,
    };
  },
};
</script>

<style scoped>
.canteen-detail-container {
  display: flex;
  background-color: #fff;
}

.back-button {
  font-size: 13px;
  border: none;
  cursor: pointer;
  margin: 0 10px;
}

.back-button:hover {
  color: #43678e;
}

.delete-button {
  font-size: 13px;
  border: none;
  cursor: pointer;
  margin: 0 10px;
}

.delete-button:hover {
  color: #43678e;
}

.sidebar {
  width: 200px;
  height: 100vh;
  border: none;
  background-color: #fff;
}

.el-menu-vertical-demo {
  border: none !important; /* 移除 el-menu 的默认边框 */
}

/* 如果需要，可以移除菜单项的边框 */
.el-menu-item {
  border: none !important;
}

.content {
  flex: 1;
  padding: 20px;
  background-color: #fff;
  margin-left: 20px;
}

.tables-section h2,
.dishes-section h2,
.reviews-section h2 {
  margin-bottom: 20px;
  color: #333;
}

.table-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.table-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 10px;
}

.table-info span {
  font-size: 16px;
  color: #333;
}

.el-button {
  margin-top: 10px;
}

.dish-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.dish-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.dish-item:hover {
  transform: translateY(-5px);
  transition: transform 0.3s ease;
}

.dish-image {
  width: 100%;
  height: 150px;
  border-radius: 8px;
  object-fit: cover;
}

.dish-info {
  text-align: center;
  margin-top: 10px;
}

.dish-info h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 5px;
}

.dish-info p {
  font-size: 16px;
  color: #43678e;
  font-weight: bold;
}


.create-post textarea {
  width: 95%;
  height: 30px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  cursor: pointer;
  margin-bottom: 20px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001 ;
}

.modal {
  background-color: #fff;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  padding: 20px;
  z-index: 1000;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.modal-header h3 {
  margin: 0;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
}

.modal-content textarea {
  width: 95%;
  height: 100px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  margin-bottom: 10px;
}

.file-input {
  margin-bottom: 10px;
}

.image-preview {
  position: relative;
  margin-bottom: 10px;
}

.image-preview img {
  width: 100%;
  border-radius: 4px;
}

.remove-image-button {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
}

.publish-button {
  padding: 8px 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.publish-button:hover {
  background-color: #0056b3;
}


.review-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.review-item {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
  position: relative;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.review-time {
  font-size: 12px;
  color: #999;
}

.review-content {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 20px;
}

.review-images {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.review-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  object-fit: cover;
}

.view-detail-button {
  position: absolute;
  bottom: 20px;
  right: 20px;
  font-size: 14px;
  color: #007bff;
}

.view-detail-button:hover {
  color: #0056b3;
}

@media (max-width: 768px) {
  .review-image {
    width: 80px;
    height: 80px;
  }

  .view-detail-button {
    position: static;
    margin-top: 10px;
  }
}
</style>
